package xienibian

/**
  * DemoClass1
  *
  * @author zhangyimin
  * @date 2018-09-20 下午2:07
  * @version 1.0
  */
class DemoClass1 {

}

//协变的例子:语法
class Animal(val name: String) {
  def say() {
    println("我是动物:" + name)
  }
}

class Bird(override val name: String, typeName: String) extends Animal(name) {
  override def say(): Unit = {
    println("我是会飞的动物:" + name)
  }
}

//协变在T前加上一个加号,代表泛型对象可以是本身,也可以是其子类
class EatFood[+T](t: T) {
  def eat(): Unit = {
    println(t.toString + "正在吃食物!")
  }
}

//逆变在T前加上一个减号,代表泛型对象可以是本身,也可以是其父类
class DrinkWater[-T](t: T) {
  def drink(): Unit = {
    println(t.toString + "正在喝水!")
  }
}


object DemoClass1 {
  def main(args: Array[String]): Unit = {
    //创建一个bird吃东西对象
    var c1: EatFood[Bird] = new EatFood[Bird](new Bird("鹦鹉", "鸟"))

    var c2: EatFood[Animal] = c1
    c1.eat()
    c2.eat()


    var d1: DrinkWater[Animal] = new DrinkWater[Animal](new Animal("喵喵"))
    d1.drink()
    var d2: DrinkWater[Bird] = d1
    d2.drink()


  }
}

